package ru.jexp.rcp.supply.swtext.properties;

import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.WidgetValueProperty;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Widget;

public class ButtonPushSelectionProperty extends WidgetValueProperty
{
	private boolean value;
	
	public ButtonPushSelectionProperty()
	{
		super(SWT.Selection);
	}

	@Override
	public Object getValueType()
	{
		return Boolean.TYPE;
	}

	protected Object doGetValue(Object source) {
		return doGetBooleanValue(source) ? Boolean.TRUE : Boolean.FALSE;
	}

	protected void doSetValue(Object source, Object value) {
		if (value == null)
			value = Boolean.FALSE;
		doSetBooleanValue(source, ((Boolean) value).booleanValue());
	}

	private boolean doGetBooleanValue(Object source)
	{
		if (value)
		{
			value = false;
			return true;
		}
		return false;
	}

	private void doSetBooleanValue(Object source, boolean value)
	{
		this.value = value; 
	}
	
	@Override
	public ISWTObservableValue observe(Widget widget)
	{
		final Button button = (Button) widget;
		button.addSelectionListener(new SelectionAdapter()
		{
			@Override
			public void widgetSelected(SelectionEvent e)
			{
				value = true;
			}
		});
		return super.observe(widget);
	}

}
